package com.irs.irsforum.web;


import com.alibaba.rocketmq.shade.com.alibaba.fastjson.JSONObject;
import com.irs.irsforum.entity.IndexPost;
import com.irs.irsforum.entity.Message;
import com.irs.irsforum.entity.Post;
import com.irs.irsforum.security.access.Access;
import com.irs.irsforum.security.access.UserType;
import com.irs.irsforum.service.IBehaviorService;
import com.irs.irsforum.service.IMessageService;
import com.irs.irsforum.service.IPostService;
import com.irs.irsforum.utils.UserMsgUtil;
import com.irs.irsforum.web.common.BaseController;
import com.irs.irsforum.web.common.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yihuili
 * @since 2020-01-18
 */
@RestController
@RequestMapping("/post")
public class PostController extends BaseController {
    private static final Logger logger =
            LoggerFactory.getLogger(PostController.class);

    private static final String SESSIONNAME = "userId";

    @Autowired
    IPostService iPostService;

    @Autowired
    IBehaviorService iBehaviorService;

    @Autowired
    IMessageService iMessageService;

    /**
     * 分页展示帖子，每页15条，并且首页展示推荐帖子，每个帖子isRecommend=1则为推荐帖
     *
     * @param currentPage 当前页
     * @param pageSize    每页大小
     * @param userMsg     用户信息串(role$id$currentTime)的加密
     * @return
     */
    @Access(userType = {UserType.UNLOGIN_USER, UserType.LOGIN_USER})
    @RequestMapping(value = "/showpostlist", method = RequestMethod.POST)
    public Object showPostByPage(@RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
                                 @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                 @RequestParam(value = "userMsg", defaultValue = "") String userMsg,
                                 HttpServletRequest request) throws Exception {

        Long userId;
        if (request.getSession().getAttribute(SESSIONNAME) == null) {
            userId = UserMsgUtil.processMsg(userMsg);
            request.getSession().setAttribute(SESSIONNAME, userId);
        } else {
            userId = (Long) request.getSession().getAttribute(SESSIONNAME);
        }
        logger.info("userId={}的人,查看currentPage={}页的帖子", userId, currentPage);
        List<IndexPost> postList = iPostService.showPostByPage(currentPage, pageSize, userId);

        return ResponseResult.newSuccessResult(postList);
    }



    /**
     * 得到页码信息以及总帖子数
     *
     * @param pageSize 每页大小默认15
     * @return
     */
    @Access(userType = {UserType.UNLOGIN_USER, UserType.LOGIN_USER})
    @RequestMapping(value = "/pagemessage", method = RequestMethod.POST)
    public Object getPageMessage(@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        logger.info("得到页码信息包括页数以及总帖子数，每页大小pageSize={}", pageSize);
        JSONObject pageMessage = iPostService.getTotalPostNum(pageSize);
        return ResponseResult.newSuccessResult(pageMessage);
    }


    /**
     * 得到单个帖子信息，并记录行为behaviorType=1，该帖子的访问量+1
     *
     * @param postId 帖子Id
     * @param userId
     * @return
     */
    @Access(userType = {UserType.LOGIN_USER})
    @RequestMapping(value = "/showpost", method = RequestMethod.POST)
    public Object showPost(@RequestParam(value = "postId") Long postId,
                           @ModelAttribute(OBJECT_USER_ATTRIBUTE) Long userId) {
        logger.info("通过postId={}，查看单个帖子", postId);
        Post post = iPostService.showPost(postId, userId);
        if (post == null) {
            logger.info("查找post失败，postId信息为={}", postId);
            return ResponseResult.newFailResult(0, "查找失败");
        } else {
            iBehaviorService.setBehaviorType(postId, userId, 1);
            return ResponseResult.newSuccessResult(post);
        }
    }

    /**
     * 添加帖子，成功之后进行行为添加以及发帖推荐。
     * 发帖推荐：
     * 1.推荐给该题正确率高的5名同学。
     * 2.如果找不足5名，则推给该题所属subject中正确率高的5名同学。
     * 3.如果找不足5名，则推给回答过或发过这个subject类别的问题的次数前5-N名同学
     * 4.如果找不足5名，则推送给老师进行回答。
     *
     * @param post 帖子  包含 content、problemId、subjectId、title
     * @return
     */
    @Access(userType = {UserType.LOGIN_USER})
    @RequestMapping(value = "/writepost", method = RequestMethod.POST)
    public Object writePost(@RequestBody Post post,
                            @ModelAttribute(OBJECT_USER_ATTRIBUTE) Long userId) {
        logger.info("写入post，post信息为={}", post.toString());
        Integer result;
        try {
            post.setUserId(userId);
            result = iPostService.writePost(post);
            if (result == 1 && userId != null) {
                iBehaviorService.setBehaviorType(post.getId(), userId, 0);
                if (post.getProblemId() != null && post.getSubjectId() != null) {
                    /*进行发帖推荐*/
                    iMessageService.writeRecommendMessage(new Message(userId, post.getId()), post.getProblemId(), post.getSubjectId());
                }
                return ResponseResult.newSuccessResult("写入成功");
            } else {
                logger.info("写入post失败，post信息为={}", post.toString());
                return ResponseResult.newFailResult("写入失败");
            }
        } catch (SQLException e) {
            logger.info("写入post失败，SQL异常，post信息为={}", post.toString());
            return ResponseResult.newFailResult("写入失败");
        }
    }

    /**
     * "我"发的贴子
     *
     * @param userId
     * @return
     */
    @Access(userType = {UserType.LOGIN_USER})
    @RequestMapping(value = "/mypost", method = RequestMethod.GET)
    public Object myPost(@ModelAttribute(OBJECT_USER_ATTRIBUTE) Long userId) {
        logger.info("用户={}所发的帖子", userId);
        List<IndexPost> postList = iPostService.getPostByUserId(userId);
        return ResponseResult.newSuccessResult(postList);
    }

    /**
     * "我"收藏的贴子
     *
     * @param userId
     * @return
     */
    @Access(userType = {UserType.LOGIN_USER})
    @RequestMapping(value = "/myfavorite", method = RequestMethod.GET)
    public Object myFavorite(@ModelAttribute(OBJECT_USER_ATTRIBUTE) Long userId) {
        logger.info("用户={}收藏的帖子", userId);
        List<IndexPost> postList = iPostService.getFavoriteByUserId(userId);
        return ResponseResult.newSuccessResult(postList);
    }

    /**
     * 删帖
     *
     * @param postId
     * @param userId
     * @return
     */
    @Access(userType = {UserType.LOGIN_USER})
    @RequestMapping(value = "/delpost", method = RequestMethod.DELETE)
    public Object delPost(@RequestParam(value = "postId") Long postId,
                          @ModelAttribute(OBJECT_USER_ATTRIBUTE) Long userId) {
        logger.info("用户={}删除帖子={}", userId, postId);
        Integer result = iPostService.delPost(postId, userId);
        if (result == 1) {
            iBehaviorService.updateBehavior(postId, userId, 1);
            return ResponseResult.newSuccessResult();
        } else {
            return ResponseResult.newFailResult("不存在该帖子");
        }

    }
}

